package com.leetcode.Offer;

import java.util.Stack;

public class JZ31_2 {
    public boolean validateStackSequences(int[] pushed, int[] popped) {
        //定义一个栈，向里面不断添加pushed元素，出现和popped相同的元素就弹出，最后判断指针是否在末端
        int a = 0, b = 0;
        Stack<Integer> stack = new Stack<>();
        while (a < pushed.length) {
            if (stack.isEmpty() || stack.peek() != popped[b]) {
                stack.push(pushed[a]);
                a++;
            }
            while (b < popped.length && !stack.isEmpty() && stack.peek() == popped[b]) {
                stack.pop();
                b++;
            }

        }
        return stack.isEmpty();
    }
}
